package com.techchat.backend.mapper;

import com.techchat.backend.model.Message;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.type.EnumTypeHandler;


import java.util.List;

@Mapper
public interface MessageMapper {

    @Insert("INSERT INTO messages(content, sender, timestamp, message_type) " +
            "VALUES(#{content}, #{sender}, #{timestamp}, #{messageType, typeHandler=org.apache.ibatis.type.EnumTypeHandler})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void insertMessage(Message message);

    @Select("SELECT id, content, sender, timestamp, message_type " +
            "FROM messages " +
            "ORDER BY timestamp ASC")
    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "content", column = "content"),
            @Result(property = "sender", column = "sender"),
            @Result(property = "timestamp", column = "timestamp"),
            @Result(property = "messageType", column = "message_type", javaType = Message.MessageType.class, typeHandler = EnumTypeHandler.class)
    })
    List<Message> findAll();

    /**
     * 在用户改昵称时，将 messages 表中所有 sender 从旧昵称更新为新昵称
     * BUG FIX: Also update sender for IMAGE messages.
     */
    @Update("UPDATE messages SET sender = #{newNickname} WHERE sender = #{oldNickname} AND (message_type = 'USER' OR message_type = 'IMAGE')")
    void updateSender(@Param("oldNickname") String oldNickname, @Param("newNickname") String newNickname);
}
